<!--
 * @Descripttion: 
 * @version: 
 * @Author: mmzhang
 * @Date: 2021-07-20 15:38:42
 * @LastEditTime: 2022-08-09 16:22:32
-->
<template>
  <div class="sub-msg">
    <p class="title">认购信息</p>
    <ul class="flex flex-wrap">
      <li class="flex" v-for="(item, index) in msgList" :key="index">
        <p class="text-right name">{{ item.name }}：</p>
        <p v-if="item.key == 'isAssociates'">
          {{ msgSub[item.key] && msgSub[item.key] != '-' ? '是' : '否' }}
        </p>
        <p v-else-if="item.key == 'isInsteadOfWorkers'">
          {{ msgSub[item.key] && msgSub[item.key] != '-' ? '是' : '否' }}
          <span v-if="msgSub[item.key] && msgSub[item.key] != '-'">
            ({{ msgSub['workersRatio'] }}%)
          </span>
        </p>
        <p v-else-if="item.key == 'auditName'">
          {{ msgSub[item.key] }}({{ msgSub['auditWorkNo'] }})
        </p>
        <p v-else-if="item.unit == ''">{{ msgSub[item.key] }}{{ item.unit }}</p>
        <p v-else>
          <span v-if="item.key == 'sumPrice'">
            {{ $tool.formatterMoney(msgSub[item.key]) }}
            <span v-if="msgSub[item.key] != '-'">{{ item.unit }}</span>
            <span v-if="adjustNum">
              ({{ adjustNum }}次调整
              <span class="view-log" @click="viewAdjustLog()">调整记录</span>
              ）
            </span>
          </span>
          <span v-else-if="msgSub.cooperationType == 6 && item.key == 'channelCost'">
            {{ msgSub.cooperationTypeName }}
          </span>
          <span v-else>
            {{ $tool.formatterMoney(msgSub[item.key]) }}
            <span v-if="msgSub[item.key] != '-'">{{ item.unit }}</span>
          </span>
        </p>
        <p
          v-if="unlocking(item.code) && item.editFlag"
          class="edit hand"
          @click="editFun(item.key)">
          修改
        </p>
      </li>
    </ul>
    <Modal v-model="subFlag" :title="title" footer-hide :width="800">
      <div>
        <Form
          ref="subForm"
          :model="subForm"
          :label-width="170"
          :rules="subValidate"
          label-position="right">
          <!--修改客户名称-->
          <FormItem label="原客户姓名：" prop="customerName" v-if="showKey == 'customerName'">
            <p>{{ subForm.customerName }}</p>
          </FormItem>
          <FormItem
            label="修改后客户姓名："
            prop="newCustomerName"
            v-if="showKey == 'customerName'">
            <Input v-model="subForm.newCustomerName" placeholder="请输入客户姓名"></Input>
          </FormItem>
          <!--修改渠道费用-->
          <FormItem label="当前渠道费用：" prop="channelCost" v-if="showKey == 'channelCost'">
            <p>{{ subForm.channelCost }}</p>
          </FormItem>
          <FormItem label="修改后渠道费用：" prop="newChannelCost" v-if="showKey == 'channelCost'">
            <Input v-model="subForm.newChannelCost" placeholder="请输入渠道费用"></Input>
          </FormItem>
          <!--修改关系户-->
          <FormItem label="是否关系户：" prop="isAssociates" v-if="showKey == 'isAssociates'">
            <RadioGroup v-model="subForm.isAssociates">
              <Radio :label="0">否</Radio>
              <Radio :label="1">是</Radio>
            </RadioGroup>
          </FormItem>
          <!--是否联代分佣-->
          <FormItem
            label="是否联代分佣："
            prop="isInsteadOfWorkers"
            v-if="showKey == 'isInsteadOfWorkers'">
            <RadioGroup v-model="subForm.isInsteadOfWorkers">
              <Radio :label="0">否</Radio>
              <Radio :label="1">是</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem
            label="分佣比例："
            prop="workersRatio"
            v-if="showKey == 'isInsteadOfWorkers' && subForm.isInsteadOfWorkers == 1">
            <Input v-model="subForm.workersRatio" type="number" placeholder="请输入分佣比例">
              <span slot="append">%</span>
            </Input>
          </FormItem>
          <!--是否渠道-->
          <FormItem label="当前客户来源渠道：" prop="channelName" v-if="showKey == 'channelName'">
            <p>{{ subForm.channelName }}</p>
          </FormItem>
          <FormItem
            label="当前渠道合作类型："
            prop="cooperationTypeName"
            v-if="showKey == 'channelName'">
            <p>{{ subForm.cooperationTypeName }}</p>
          </FormItem>
          <FormItem label="当前渠道费用：" prop="channelCost" v-if="showKey == 'channelName'">
            <p>
              {{ subForm.channelCost }}
              <span v-if="subForm.channelCost != '无'">{{ subForm.channelUnit }}</span>
            </p>
          </FormItem>
          <FormItem
            label="修改后客户来源渠道："
            prop="newChannelId"
            v-if="showKey == 'channelName'">
            <!-- <Cascader :data="channelList" :render-format="formatChannel"
              v-model="subForm.newChannelId" placeholder="请选择" @on-change="changeChannel">
            </Cascader> -->
            <div class="radioNine" v-if="subFlag">
              <RadioGroup :v-model="subForm.newChannelId" @on-change="changeChannel" type="button">
                <Radio v-for="item in channelList" :key="item.channelId" :label="item.channelId">
                  <!-- {{ item.channelName }} -->
                  <span
                    :title="item.channelName"
                    style="
                      display: inline-block;
                      width: 100%;
                      overflow: hidden;
                      white-space: nowrap;
                      text-overflow: ellipsis;
                    ">
                    {{ item.channelName }}
                  </span>
                  <span v-if="item.isTakeLook == '1'" class="qu">渠</span>
                  <span v-if="item.isNetAcquire == '1'" class="wang">网</span>
                </Radio>
              </RadioGroup>
            </div>
          </FormItem>

          <FormItem label="修改后渠道合作类型：" prop="newChannelType1" v-if="cooperationFlag">
            <Select
              v-model="subForm.newChannelType1"
              placeholder="请输入合作类型"
              @on-change="newChannelType1Channel"
              clearable>
              <Option
                v-for="option in cooperationTypeFinal"
                :value="option.key"
                :key="option.key"
                :label="option.value"></Option>
            </Select>
          </FormItem>

          <FormItem
            label="修改后渠道合作类型："
            prop="newChannelType"
            v-if="showKey == 'channelName' && subForm.newChannelType != '' && !cooperationFlag">
            <p>{{ subForm.newChannelType }}</p>
          </FormItem>
          <!--线下投放，客户运营不展示附件-->
          <FormItem label="渠道附件：" prop="showChannelImg" class="annex-list" v-if="filesFlag">
            <!-- <FormItem label="渠道附件：" prop="showChannelImg" class="annex-list"> -->
            <enclosure-img
              :images="subForm.showChannelImg"
              :alreayDel="true"
              @onHandleRemove="handleRemove"></enclosure-img>
            <upload-enclosure
              @onHandleSuccess="handleSuccess"
              :images="subForm.showChannelImg"
              :disabledFlag="disabledFlag"
              v-if="subForm.showChannelImg.length < 30"></upload-enclosure>
          </FormItem>
          <FormItem class="flex flex-horizontal-end">
            <Button @click="cancelSub" style="margin-right: 20px">取消</Button>
            <Button type="primary" @click="submitSub">确定</Button>
          </FormItem>
        </Form>
      </div>
    </Modal>
    <!--认购调整-->
    <sub-adjust-detail ref="subAdjustDetail" :detailMsg="detailMsg"></sub-adjust-detail>
  </div>
</template>
<script>
  import enclosureImg from '@/components/enclosureImg.vue'
  import uploadEnclosure from './uploadEnclosure.vue'
  import subAdjustDetail from './subAdjustDetail.vue'
  import comMgr from '@/biz/sales/salesCommon'
  import channelMgr from '@/biz/channel/channel.js'
  export default {
    // 认购未签约可编辑
    props: ['detailMsg', 'orderId', 'buildingId'],
    data() {
      let numberPass = (rule, value, callback) => {
        let reg = /^([0-9]{1,2}|100)$/
        if (value && !reg.test(value)) {
          callback(new Error('请输入0-100内的数字'))
        } else {
          callback()
        }
      }

      let costPass = (rule, value, callback) => {
        let reg = /^([0-9]+[\d]*(.[0-9]{1,2})?)$/
        if (value && !reg.test(value)) {
          callback(new Error('请输入数字,最多保留两位小数'))
        } else {
          callback()
        }
      }
      return {
        filesFlag: false,
        cooperationTypeFinal: this.$dt.dictInfo().cooperationTypeFinal,
        // newChannelType1: null,
        cooperationFlag: false,

        disabledFlag: false,
        upLoadFlag: true,
        statusName: '',
        titleList: [
          {
            key: 'customerName',
            title: '客户姓名修改',
            value: 'EDIT_CUSTOMER_NAME'
          },
          {
            key: 'channelCost',
            title: '渠道费用修改',
            value: 'EDIT_CHANNEL_COST'
          },
          {
            key: 'isAssociates',
            title: '是否关系户修改',
            value: 'EDIT_IS_ASSOCIATES'
          },
          {
            key: 'isInsteadOfWorkers',
            title: '是否联代分佣修改',
            value: 'EDIT_IS_INSTEADOF_WORKERS'
          },
          {
            key: 'channelName',
            title: '渠道修改',
            value: 'EDIT_CHANNEL'
          }
        ],
        title: '',
        subFlag: false,
        subForm: {
          customerName: '',
          newCustomerName: '',
          isInsteadOfWorkers: '', // 是否联代分佣
          workersRatio: '', // 分佣比例
          isAssociates: '', // 是否关系户
          showChannelImg: [],
          channelName: '',
          cooperationTypeName: '', // 合作类型
          channelCost: '', // 渠道费用
          channelUnit: '', // 渠道费用单位
          newChannelId: '', // 修改后渠道
          newChannelType: '', // 修改后的渠道合作类型
          newChannelCost: '', // 修改后渠道费用
          newChannelType1: null
        },
        subValidate: {
          newChannelType1: [
            {
              required: true,
              message: '屋拉的合作渠道不能为空',
              trigger: 'change'
            }
          ],
          newCustomerName: [
            {
              required: true,
              message: '客户姓名不能为空',
              trigger: 'blur'
            }
          ],
          newChannelCost: [
            {
              required: true,
              message: '渠道费用不能为空',
              trigger: 'blur'
            },
            { validator: costPass, trigger: 'blur', required: false }
          ],
          workersRatio: [
            {
              required: true,
              message: '分佣比例不能为空',
              trigger: 'blur'
            },
            { validator: numberPass, trigger: 'blur', required: false }
          ],
          newChannelId: [
            {
              required: true,
              message: '来源渠道不能为空',
              trigger: 'blur',
              type: 'number'
            }
          ]
        },
        preImages: [],
        msgList: [
          {
            name: '认购客户',
            key: 'customerName',
            edit: true,
            unit: '',
            code: '0104010302'
          },
          {
            name: '客户手机号',
            key: 'customerPhone',
            edit: false,
            unit: '',
            code: ''
          },
          {
            name: '认购单价',
            key: 'price',
            edit: false,
            unit: '元',
            code: ''
          },
          {
            name: '认购总价',
            key: 'sumPrice',
            edit: false,
            unit: '元',
            code: ''
          },
          {
            name: '定金金额',
            key: 'deposit',
            edit: false,
            unit: '元',
            code: ''
          },
          {
            name: '是否关系户',
            key: 'isAssociates',
            edit: true,
            unit: '',
            code: '0104010303'
          },
          {
            name: '是否联代分佣',
            key: 'isInsteadOfWorkers',
            edit: true,
            unit: '',
            code: '0104010304'
          },
          {
            name: '来源渠道',
            key: 'channelName',
            edit: true,
            unit: '',
            code: '0104010306'
          },
          {
            name: '合作类型',
            key: 'cooperationTypeName',
            edit: false,
            unit: '',
            code: ''
          },
          {
            name: '渠道费用',
            key: 'channelCost',
            edit: true,
            unit: '元',
            code: '0104010311'
          },
          {
            name: '预计签约日期',
            key: 'signedDate',
            edit: false,
            unit: '',
            code: ''
          },
          {
            name: '创建时间',
            key: 'createTime',
            edit: false,
            unit: '',
            code: ''
          },
          {
            name: '审核人',
            key: 'auditName',
            edit: false,
            unit: '',
            code: ''
          },
          {
            name: '审核时间',
            key: 'auditDate',
            edit: false,
            unit: '',
            code: ''
          }
        ],
        msgSub: {},
        showKey: '',
        channelList: [],
        cooperationTypeList: [],
        adjustNum: 0
        // isFlag: null,
      }
    },
    components: {
      enclosureImg,
      uploadEnclosure,
      subAdjustDetail
    },
    created() {},
    async mounted() {
      await this.getChannelList()
      this.msgSub = { ...this.detailMsg.orContractWebInfoVO }
      this.adjustNum = this.detailMsg.orAdjustmentDetailVOList.length
      let filterVal = this.$dt
        .dictInfo()
        .cooperationTypeFinal.filter((item) => item.dictValue == this.msgSub.cooperationType)
      this.msgSub.cooperationTypeName =
        this.msgSub.cooperationTypeName != '-'
          ? this.msgSub.cooperationTypeName
          : filterVal.length
          ? filterVal[0].dictLabelCn
          : '无'
      this.msgSub.channelUnit = filterVal.length ? filterVal[0].unit : ''
      this.statusName = this.detailMsg.orContractBaseInfoVO.statusName
      // 处理修改按钮逻辑
      this.msgList.forEach((item) => {
        item.editFlag = this.showEditFun(item)
      })
    },
    methods: {
      // 是否可编辑
      showEditFun(item) {
        let flag = false
        if (item.key == 'channelCost') {
          if (
            [
              '认购待审核',
              '认购未签约',
              '认购退购中',
              '认购已退购',
              '认购已退签',
              '认购已签约'
            ].indexOf(this.statusName) > -1 &&
            ['1', '2'].indexOf(this.msgSub.cooperationType) > -1
          ) {
            // 认购单处于“待审核、未签约、退购中、已退购、已退签、已签约”，且合作类型为“同策合作”与“开发商合作”
            flag = true
          } else {
            flag = false
          }
        } else if (this.statusName == '认购未签约' && item.edit) {
          flag = true
        } else {
          flag = false
        }
        return flag
      },
      newChannelType1Channel(val) {
        // console.log(val, 'vvvvvvv');
        // if (val == '7') {
        //   this.filesFlag = false
        // } else {
        //   this.filesFlag = true
        // }
      },
      showChannelImgFun() {
        let flag1 = false
        let changeChannelId = this.subForm.newChannelId
          ? this.subForm.newChannelId
          : this.subForm.channelId
        this.channleAnnexLogList().then((res) => {
          let annexFiles = []
          let currentChannel = this.channelList.find((item) => {
            return item.channelId == changeChannelId
          })

          console.log(currentChannel, 'currentChannelcurrentChannel')
          if (
            currentChannel &&
            (currentChannel.isNetAcquire == '1' || currentChannel.isTakeLook == '1')
          ) {
            if (currentChannel.cooperationType != '7') {
              flag1 = true
              if (res && res.length) {
                let currentAnnex = res.find((annexItem) => {
                  return annexItem.channelId == currentChannel.channelId
                })
                if (currentAnnex && currentAnnex.url) {
                  let annexUrl = JSON.parse(currentAnnex.url)
                  if (annexUrl && annexUrl.length > 0) {
                    annexUrl.forEach((itemUrl) => {
                      if (itemUrl) {
                        annexFiles.push({
                          name: itemUrl.date,
                          url: itemUrl.url
                        })
                      }
                    })
                    this.$set(this.subForm, 'showChannelImg', annexFiles)
                  }
                } else {
                  this.$set(this.subForm, 'showChannelImg', [])
                }
              }
            } else {
              flag1 = false
            }
          } else {
            flag1 = false
          }
          if (this.showKey == 'channelName' && flag1) {
            this.filesFlag = true
          } else {
            this.filesFlag = false
          }
        })
      },
      formatChannel(labels, selectedData) {
        if (selectedData.length) {
          const index = labels.length - 1
          return labels[index]
        }
      },
      // 渠道修改  线下投放 客户运营(1,4) 隐藏附件上传   网络媒体2 渠道带看3显示附件上传
      changeChannel(val) {
        this.subForm.newChannelId = val
        let cooperationTypetype = null
        let cooperationTypeName = null
        let currentChannel = this.channelList.find((item) => {
          return item.channelId == this.subForm.newChannelId
        })
        if (currentChannel) {
          cooperationTypeName = currentChannel.cooperationTypeName
          cooperationTypetype = currentChannel.cooperationType
        }
        this.subForm.newChannelType = cooperationTypeName ? cooperationTypeName : '无'
        if (cooperationTypetype == '6') {
          this.cooperationFlag = true
        } else {
          this.cooperationFlag = false
        }
        this.showChannelImgFun()
      },
      //获取渠道附件
      channleAnnexLogList() {
        let params = {
          businessId: this.$route.query.businessId,
          housesId: this.buildingId ? this.buildingId : this.$dt.buildInfo().housesId,
          type: 'subscription'
        }
        return channelMgr.channleAnnexLogList(params).then((res) => {
          this.annexLogList = res
          return res
        })
      },
      // 渠道列表
      getChannelList() {
        let params = {
          validate: 1,
          type: 1,
          buildingId: this.buildingId ? this.buildingId : this.$dt.buildInfo().housesId
        }
        return channelMgr
          .caseChannelListOrder(params)
          .then((res) => {
            this.channelList = res
          })
          .catch((res) => {
            this.channelList = []
          })
      },
      editFun(key) {
        this.showKey = key
        this.$nextTick(function () {
          this.title = this.titleList.filter((item) => item.key == key)[0].title
          this.subForm = this.$tool.deepClone(Object.assign(this.subForm, this.msgSub))
          this.$tool.transformationNullSet(this.subForm)
          this.subForm.isAssociates = this.subForm.isAssociates ? 1 : 0
          this.subForm.isInsteadOfWorkers = this.subForm.isInsteadOfWorkers ? 1 : 0
          // this.subForm.showChannelImg = this.resolveChannelImg(
          //   this.msgSub.channelType
          // )
          this.subForm.channelCost = this.subForm.channelCost ? this.subForm.channelCost : '无'
          this.subFlag = true
          switch (this.showKey) {
            case 'customerName':
              this.newKey = 'newCustomerName'
              this.isKey = ''
              break
            case 'channelCost':
              this.newKey = 'newChannelCost'
              this.isKey = ''
              break
            case 'isAssociates':
              this.newKey = ''
              this.isKey = key
              break
            case 'isInsteadOfWorkers':
              this.newKey = 'workersRatio'
              this.isKey = key
              break
            case 'channelName':
              this.newKey = 'newChannelId'
              this.isKey = ''
              break
            default:
              break
          }
          this.showChannelImgFun()
          console.log(this.subForm, 'subFormsubFormsubForm')
        })
      },
      cancelSub() {
        this.$refs.subForm.resetFields()
        this.subFlag = false
      },
      viewAdjustLog() {
        this.$refs.subAdjustDetail.show()
      },
      submitSub() {
        // if (
        //   (this.subForm.newChannelId[0] == 2 ||
        //     this.subForm.newChannelId[0] == 3) &&
        //   !this.subForm.showChannelImg.length &&
        //   this.showKey == 'channelName'
        // ) {
        //   this.$Message.error('渠道附件不能为空')
        //   return false
        // }
        this.$refs['subForm'].validate((valid) => {
          if (valid) {
            let params = {
              operateType: this.titleList.filter((item) => item.key == this.showKey)[0].value,

              fileAddress: JSON.stringify(this.subForm.showChannelImg),

              is: !this.subForm[this.isKey] ? false : true,

              newValue:
                this.showKey == 'channelName'
                  ? this.subForm.newChannelId
                  : this.subForm[this.newKey],

              orderId: this.orderId,

              cooperationType: this.subForm.newChannelType1 ? this.subForm.newChannelType1 : null
            }

            // 提交认购信息
            comMgr
              .editOrderInfo(params)
              .then((res) => {
                this.contractFlag = false
                this.$Message.success(this.title + '成功！')
                this.$emit('onGetOrderDetail')
              })
              .catch((res) => {})
          }
        })
      },
      //移除图片
      handleRemove(index, type) {
        this.subForm.showChannelImg.splice(index, 1)
      },
      // 上传成功
      handleSuccess(file, type) {
        file.forEach((item) => {
          this.subForm.showChannelImg.push({
            url: item.url,
            date: this.$tool.formatDate(new Date())
          })
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .radioNine {
    padding: 5px;
    display: flex;
    justify-content: space-around;
    flex-direction: row;
    height: 300px;
    overflow-y: auto;
  }

  .radioNine label {
    width: 25%;
    text-align: center;
    line-height: 30px !important;
    height: 30px !important;
    position: relative;
  }

  .radioNine label span.qu {
    position: absolute;
    top: -8px;
    right: 0;
    color: #ff9900;
  }

  .radioNine label span.wang {
    position: absolute;
    top: -8px;
    right: 0;
    color: #ed4014;
  }

  .radioNine .ivu-radio-group-button .ivu-radio-wrapper-checked {
    border-color: #2d8cf0;
    background-color: #2d8cf0;
    box-shadow: -1px 0 0 0 #2d8cf0;
    color: #fff;
  }

  .sub-msg {
    margin-top: 40px;

    ul {
      li {
        width: 50%;
        line-height: 50px;

        .name {
          width: 150px;
        }

        .edit {
          margin-left: 10px;
          color: #2d8cf0;
          font-size: 14px;
        }
      }

      .view-log {
        margin-left: 5px;
        color: #2d8cf0;
        cursor: pointer;
      }
    }

    .ivu-upload-drag {
      width: 100px;
    }
  }

  ::v-deep .annex-list {
    .ivu-form-item-content {
      display: flex;
      flex-flow: wrap;
    }
  }
</style>
